<template>
  <div class="app-container table-app-container">
    <el-row :gutter="8">
      <el-col :span="4">
        <el-tree ref="tree" class="filter-tree relainst-page-tree" :data="treeData" :props="treeProps" node-key="_id" :default-expanded-keys="['']" @node-click="onTreeSelected" />
      </el-col>
      <el-col :span="20">
        <div v-loading="uploading" class="fixed-table">
          <div class="fixed-table-actionbar">
            <table-filter
              :relation-id="context._id"
              @on-filter="searchContext"
            />
            <action-bar
              :relation-id="context._id"
              :download-tpl-completed="downloadTplCompleted"
              @on-remove="onRemove"
              @on-download-tpl="downloadTpl"
              @on-before-upload="onBeforeUpload"
              @on-success-upload="onSuccessUpload"
              @on-fail-upload="onFailUpload"
            />
          </div>
          <PageableTable
            v-if="insideColumns.length > 0"
            :key="tableKey"
            :loading="loading"
            :data="insideTableData"
            :total="totalElements"
            :page="currentPage"
            :page-size="pageSize"
            :table-height="tableHeight"
            class="fixed-table-table"
            :multiple-selected="true"
            @page-change="onPageChange"
            @sort-change="onSortChange"
            @selection-change="onSelectionChange"
          >
            <el-table-column v-for="column in insideColumns" :key="column.key" :label="column.title" :prop="column.key" :sortable="column.sortable">
              <template slot-scope="scope">
                <column-render :render="column.render" :row="scope.row" :column="column" />
              </template>
            </el-table-column>
          </PageableTable>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// secondary package based on el-pagination
import ActionBar from './components/actionBar'
import TableFilter from './components/tableFilter'
import PageableTable from '@neu/biz-core/components/PageableTable'
import { deepClone } from '@neu/biz-core/utils'
import { detail as relationDetail, simpleList as relationTree, getTpl } from '@neu/cmdb-ui/api/relation'
import { remove, pageByRelation, batchRemove } from '@neu/cmdb-ui/api/relationinstance'
import databind from '@neu/biz-core/mixins/databind'

export default {
  name: 'RelationListPage',
  components: {
    PageableTable,
    ActionBar,
    TableFilter
  },
  mixins: [databind],
  data() {
    return {
      r: '',
      d: remove,
      ds: batchRemove,
      treeProps: {
        children: 'children',
        label: 'desc'
      },
      treeData: [],
      tableKey: '',
      context: {
        _id: ''
      },
      insideColumns: [],
      uploading: false,
      downloadTplCompleted: false
    }
  },
  created() {
    const relationId = this.$route.query.relation
    // 必须先加载模型树，然后在请求具体模型下的实例
    relationTree().then(response => {
      // 添加一个虚拟顶点
      const treeData = [{
        _id: '',
        desc: '所有关系',
        children: response.data
      }]
      response.data.forEach(it => {
        if (it._id === relationId) {
          this.onTreeSelected(it)
        }
      })
      this.treeData = treeData
    })
  },
  methods: {
    responseFormatter(data) {
      const formatData = data.map(it => {
        const { _id, attrs, ...others } = it
        const mAttrs = attrs.reduce((o, item) => { o[item.key] = item.value; return o }, {})
        const d = {
          _id,
          ...mAttrs,
          ...others
        }
        // 保留记录的原始值，在取消编辑时，可恢复原始值
        d.v0 = Object.freeze(deepClone(d))
        return d
      })
      return formatData
    },
    searchContext(query) {
      query = { ...query }
      this.filter(query)
    },
    onRemove() {
      this.remove(this.selections.map(it => { return { id: it._id } }))
    },
    onTreeSelected: async function(data, node) {
      if (data._id === '') {
        return
      }
      this.context = data
      const routePath = this.$route.path
      this.$router.push({ routePath, query: { relation: data._id }})
      this.tableKey = data._id

      const columns = [
        { title: '描述', key: 'desc' },
        {
          title: '源实例',
          key: 'src.name',
          render: (h, params) => {
            return (
              <router-link to={'/cmdb/instances/' + params.row.src._id} class={'el-link el-link--primary'}>{ params.row.src.name }</router-link>
            )
          }
        },
        {
          title: '目标实例',
          key: 'dest.name',
          render: (h, params) => {
            return (
              <router-link to={'/cmdb/instances/' + params.row.dest._id} class={'el-link el-link--primary'}>{ params.row.dest.name }</router-link>
            )
          }
        },
        {
          title: '所属关联',
          key: 'rela.desc',
          render: (h, params) => {
            return (
              h('span', params.row.rela.desc)
            )
          }
        }
      ]

      const response = await relationDetail(data._id)
      const relaInfo = response.data
      let mAttrs = []
      if (relaInfo.attrs) {
        mAttrs = [...relaInfo.attrs]
      }
      mAttrs.forEach(attr => {
        columns.push({
          title: attr.name,
          key: attr.field,
          render: (h, params) => {
            return h('span', params.row[attr.field])
          }
        })
      })
      this.insideColumns = []
      this.insideColumns = deepClone(columns)

      this.r = pageByRelation(data._id)
      this.filter()
    },
    downloadTpl() {
      const that = this
      that.downloadTplCompleted = true
      getTpl(this.context._id).then(response => {
        that.downloadTplCompleted = false
        const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
        let filename = response.headers['content-disposition']
        if (filename) {
          filename = decodeURI(filename.split('=')[1]) // 提取文件名
        } else {
          filename = that.context.name + '导出信息.xlsx'
        }
        if ('download' in document.createElement('a')) { // 非IE下载
          const elink = document.createElement('a')
          elink.download = filename
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else { // IE10+下载
          navigator.msSaveBlob(blob, filename)
        }
      })
    },
    onBeforeUpload() {
      this.uploading = true
    },
    onSuccessUpload(count) {
      this.uploading = false
      this.refresh()
      this.$message({
        showClose: true,
        message: '上传成功（' + count + '）',
        type: 'success'
      })
    },
    onFailUpload(error) {
      this.uploading = false
      this.$message({
        showClose: true,
        message: error,
        type: 'error'
      })
    }
  }
}
</script>

<style>
.relainst-page-tree .el-tree-node__children {
  overflow-x: auto!important;
}
</style>
